package dbutils;

import org.junit.Test;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 仿commons-dbutils
 * Created by kevin on 2020/4/2.
 */
public class Demo2 {
    @Test
    public void fun1(){
//        Stu stu = new Stu();
//        stu.setNumber("0002");
//        stu.setName("王五");
//        stu.setAge(30);
//        stu.setGender("男");
//        stu.setPassword("111111");
//        add(stu);

        Stu stu2 = load("0002");
        System.out.println(stu2.toString());
    }

    public int add(Stu stu){
        QR<Stu> stuQr = new QR<Stu>(JdbcUtils.getDataSource());
        String sql="insert into stu values(?,?,?,?,?)";
        Object[] params = {stu.getNumber(),stu.getName(),stu.getAge(),stu.getGender(),stu.getPassword()};
        return stuQr.update(sql,params);
    }

    public Stu load(String number){
        QR<Stu> stuQr = new QR<Stu>(JdbcUtils.getDataSource());
        String sql="select * from stu where number=?";
        Object[] params = {number};
        RsHandler<Stu> rh = new RsHandler<Stu>() {
            @Override
            public Stu handle(ResultSet rs) throws SQLException{
                if(!rs.next())  return null;
                Stu stu = new Stu();
                stu.setNumber(rs.getString("number"));
                stu.setName(rs.getString("name"));
                stu.setAge(rs.getInt("age"));
                stu.setGender(rs.getString("gender"));
                stu.setPassword(rs.getString("password"));
                return stu;
            }
        };
        return stuQr.query(sql,rh,params);
    }
}
